<template>
  <div class="login-container">
    <el-card class="login-card">
      <h2 style="text-align: center; margin-bottom: 30px;">系统注册</h2>

      <el-form :model="registerForm" @submit.prevent="handleRegister">
        <el-form-item>
          <el-input
              v-model="registerForm.userName"
              placeholder="用户名"
              prefix-icon="User"
              size="large"
          />
        </el-form-item>

        <el-form-item>
          <el-input
              v-model="registerForm.pwd"
              placeholder="请输入密码"
              prefix-icon="Lock"
              type="password"
              size="large"
          />
        </el-form-item>
        <el-form-item>
          <el-input
              v-model="registerForm.wpwd"
              placeholder="确认密码"
              prefix-icon="Lock"
              type="password"
              show-password
              size="large"
          />
        </el-form-item>
        <el-form-item>
          <el-input
              v-model="registerForm.email"
              placeholder="请输入QQ邮箱"
              prefix-icon="Message"
              type="text"
              size="large"
          />
        </el-form-item>
        <el-form-item>
          <div class="code-input-container">
            <el-input
                v-model="registerForm.code"
                placeholder="请输入验证码"
                prefix-icon="Key"
                size="large"
                style="flex: 1; margin-right: 10px;"
            />
            <el-button
                type="primary"
                :disabled="isCountingDown"
                @click="sendCode"
                style="width: 120px;"
            >
              {{ countdown > 0 ? `${countdown}秒后重试` : '获取验证码' }}
            </el-button>
          </div>
        </el-form-item>
        <el-form-item style="margin-top: 30px;">
          <el-button
              type="primary"
              native-type="submit"
              style="width: 100%; height: 50px; font-size: 16px;"
              :loading="isLoading"
          >
            注册
          </el-button>
        </el-form-item>
      </el-form>
      <div class="login-footer">
        <el-button type="text" @click="router.push('/yycsh')">已有账号？去登录</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage, ElLoading } from 'element-plus'
import axios from "axios";
import {useRouter} from 'vue-router'
const router = useRouter()

const registerForm = ref({
  userName: '',
  pwd: '',
  wpwd: '',
  email: '',
  code: ''
})

const isCountingDown = ref(false)
const countdown = ref(0)
const isLoading = ref(false)
const verifyCode = ref('') // 存储生成的验证码

// 发送验证码
const sendCode = async () => {
  // 简单验证
  if (!registerForm.value.userName) return ElMessage.warning('请输入用户名')
  if (!/^[1-9]\d{4,10}@qq\.com$/.test(registerForm.value.email)) {
    return ElMessage.warning('请输入正确的QQ邮箱')
  }

  try {
    // 检查用户名是否已存在
    const userData = await axios.get(`/api/user/getUserByUserName/${registerForm.value.userName}`)
    if (userData.data) return ElMessage.error('用户名已存在')

    // 检查邮箱是否已注册
    const {data} = await axios.get(`/api/user/getUserByEmail/${registerForm.value.email}`)
    if (data) return ElMessage.error('该邮箱已被注册')

    // 生成验证码
    const code = Math.floor(1000 + Math.random() * 9000).toString()
    verifyCode.value = code

    // 发送邮件
    const loading = ElLoading.service({ text: '发送中...' })
    await axios.get(`/api/user/sendEmail/${registerForm.value.email}/验证码/您的验证码是：${code}`)
    loading.close()

    ElMessage.success('验证码已发送到邮箱')

    // 开始倒计时
    startCountdown()
  } catch (error) {
    ElMessage.error('发送失败，请重试')
  }
}

// 倒计时
const startCountdown = () => {
  countdown.value = 60
  isCountingDown.value = true
  const timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(timer)
      isCountingDown.value = false
    }
  }, 1000)
}

// 注册
const handleRegister = async () => {
  // 表单验证
  console.log(registerForm.value)
  if (!registerForm.value.userName) return ElMessage.warning('请输入用户名')
  if (!registerForm.value.email) return ElMessage.warning('请输入邮箱')
  if (!registerForm.value.code) return ElMessage.warning('请输入验证码')
  if (registerForm.value.code !== verifyCode.value) return ElMessage.error('验证码错误')
  if (registerForm.value.pwd.length < 6) return ElMessage.warning('密码长度不能少于6位')
  if (registerForm.value.pwd !== registerForm.value.wpwd) return ElMessage.error('两次密码不一致')

  try {
    isLoading.value = true

    // 提交注册
    const res = await axios.post('/api/user', registerForm.value)

    if (res.data) {
      ElMessage.success('注册成功')
      setTimeout(() => router.push('/yycsh/'), 1500)
    } else {
      ElMessage.error('注册失败')
    }
  } catch (error) {
    ElMessage.error('注册失败，请重试')
  } finally {
    isLoading.value = false
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  position: fixed;
  right: 20px;
  align-items: center;
  min-height: 100vh;
  width: 500px;
}

.login-card {
  width: 100%;
  max-width: 400px;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.code-input-container {
  display: flex;
  align-items: center;
}

.el-input {
  height: 50px;
  font-size: 16px;
}
</style>